package co.yixiang.hw.service.impl;

import co.yixiang.hw.domain.YxStoreOrder;
import co.yixiang.hw.domain.YxStoreOrderCartInfo;
import co.yixiang.hw.service.YxStoreCouponUserService;
import co.yixiang.hw.service.YxStoreProductService;
import co.yixiang.hw.service.dto.YxStoreOrderDto;
import co.yixiang.hw.service.dto.YxStoreProductDto;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.hw.repository.YxStoreOrderCartInfoRepository;
import co.yixiang.hw.service.YxStoreOrderCartInfoService;
import co.yixiang.hw.service.dto.YxStoreOrderCartInfoDto;
import co.yixiang.hw.service.dto.YxStoreOrderCartInfoQueryCriteria;
import co.yixiang.hw.service.mapper.YxStoreOrderCartInfoMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @author Walert
* @date 2020-02-13
*/
@Service
//@CacheConfig(cacheNames = "yxStoreOrderCartInfo")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxStoreOrderCartInfoServiceImpl implements YxStoreOrderCartInfoService {

    @Resource
    private  YxStoreOrderCartInfoRepository yxStoreOrderCartInfoRepository;
    @Resource
    private  YxStoreOrderCartInfoMapper yxStoreOrderCartInfoMapper;

    @Autowired
    private YxStoreProductService yxStoreProductService;

    @Autowired
    private YxStoreCouponUserService couponUserService;


    @Override
    //@Cacheable
    public Map<String,Object> queryAll(YxStoreOrderCartInfoQueryCriteria criteria, Pageable pageable){
        Page<YxStoreOrderCartInfo> page = yxStoreOrderCartInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(yxStoreOrderCartInfoMapper::toDto));
    }

    @Override
    //@Cacheable
    public List<YxStoreOrderCartInfoDto> queryAll(YxStoreOrderCartInfoQueryCriteria criteria){
        return yxStoreOrderCartInfoMapper.toDto(yxStoreOrderCartInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public YxStoreOrderCartInfoDto findById(Integer id) {
        YxStoreOrderCartInfo yxStoreOrderCartInfo = yxStoreOrderCartInfoRepository.findById(id).orElseGet(YxStoreOrderCartInfo::new);
        ValidationUtil.isNull(yxStoreOrderCartInfo.getId(),"YxStoreOrderCartInfo","id",id);
        return yxStoreOrderCartInfoMapper.toDto(yxStoreOrderCartInfo);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public YxStoreOrderCartInfoDto create(YxStoreOrderCartInfo resources) {

        return yxStoreOrderCartInfoMapper.toDto(yxStoreOrderCartInfoRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(YxStoreOrderCartInfo resources) {
        YxStoreOrderCartInfo yxStoreOrderCartInfo = yxStoreOrderCartInfoRepository.findById(resources.getId()).orElseGet(YxStoreOrderCartInfo::new);
        ValidationUtil.isNull( yxStoreOrderCartInfo.getId(),"YxStoreOrderCartInfo","id",resources.getId());
        yxStoreOrderCartInfo.copy(resources);
        yxStoreOrderCartInfoRepository.save(yxStoreOrderCartInfo);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            yxStoreOrderCartInfoRepository.deleteById(id);
        }
    }


    @Override
    public void saveOrderCartInfo(YxStoreOrderDto order, JSONArray goodsList){
        int size = goodsList.size();
        //订单商品信息保存
        for (int i = 0; i < size; i++) {
            JSONObject goodsObject = goodsList.getJSONObject(i);
            YxStoreOrderCartInfo cartInfo = new YxStoreOrderCartInfo();
            Integer productId = goodsObject.getInteger("productId");
            Integer cartId = goodsObject.getInteger("cartId");
            Integer cartNum = goodsObject.getInteger("cartNum");
            cartInfo.setOid(order.getId());
            if(cartId != null && cartId > 0) cartInfo.setCartId(cartId);
            else cartInfo.setCartId(0);
            cartInfo.setProductId(productId);
            YxStoreProductDto productInfo = yxStoreProductService.findById(productId);
            JSONObject coupon = goodsObject.getJSONObject("coupon");
            JSONObject cartInfoObj = new JSONObject();
            cartInfoObj.put("type","product");
            cartInfoObj.put("truePrice",productInfo.getPrice());
            cartInfoObj.put("cartNum",cartNum);
            cartInfoObj.put("productInfo",productInfo);
            cartInfoObj.put("couponPrice",0);
            if(coupon != null){
                cartInfoObj.put("coupon",coupon);
                Integer ucid = coupon.getInteger("id");
                couponUserService.useCoupon(ucid,order.getOrderId());
                BigDecimal price = coupon.getBigDecimal("couponPrice");
                cartInfoObj.put("couponPrice",price);
            }
            cartInfo.setCartInfo(cartInfoObj.toJSONString());
            this.create(cartInfo);
        }
    }
}